//封装购物车模块

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user.js'
import {insertCartAPI,findNewCartListAPI,delCartAPI} from '@/api/cart.js'

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const cartList = ref([])
    const updateNewList=async ()=>{
        const res=await findNewCartListAPI()
        cartList.value=res.result
    }
    const isLogin = computed(() => userStore.userInfo.token)
    const addCart = async (goods) => {
        if (isLogin.value) {
            //登录之后的加入购物车逻辑
            const {skuId,count} = goods
           await insertCartAPI({skuId,count})
           updateNewList()
        } else {
            //添加购物车
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                item.count++
            } else {
                cartList.value.push(goods)
            }
        }
    }

    const delCart = async (skuId) => {
        if(isLogin.value){
            await delCartAPI([skuId])
            updateNewList()
        }else{
            cartList.value = cartList.value.filter(item => item.skuId != skuId)
        }
        
    }

    const clearCart=()=>{
        cartList.value=[]
    }

    //单选功能
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }

    //全选功能
    const allCheck = (selected) => {
        //把cartList中的每一项的selected都设置位当前的全选框状态
        cartList.value.forEach(item => item.selected = selected)
    }

    //计算属性
    //计算所有项
    const allCount = computed(() => cartList.value.reduce((count, item) => item.count + count, 0))

    //计算所有项的总价
    const allPrice = computed(() => cartList.value.reduce((count, item) => item.price * item.count + count, 0))

    //已选择数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((count, item) => item.count + count, 0))

    //已选择商品价钱合计
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((count, item) => item.price * item.count + count, 0))


    //是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    return {
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singleCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList
    }
},
    {
        persist: true,
    }
)